from rest_framework.response import Response
from rest_framework.views import APIView

from my.models import User
from api.serializers import UserSerializer


# Create your views here.
class LoginView(APIView):
    # 登录不进行jwt验证
    authentication_classes = ()
    permission_classes = ()
    serializer_class = UserSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():# 当校验通过执行
            return Response(serializer.validated_data)
        return Response({"code":2, "msg":"登陆失败", "data":None})

class RegView(APIView):
    # 注册不进行jwt验证
    authentication_classes = ()
    permission_classes = ()

    def post(self, request):
        # 添加用户到user数据库中
        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(username=username).first()
        if not user:
            User.objects.create_user(username=username, password=password)
            return Response({"code":0, "msg":"注册成功！", "data":None})
        return Response({"code":2, "msg":"注册失败！", "data":None})
